package com.ThreadSyncEg;
// 线程死锁 synchronized{}
// 2个对象冲突
public class DeadLock extends Thread{

    //static 类加载时初始化 保证对象数量不会变化
    static Object o1 = new Object();
    static Object o2 = new Object();

    boolean flag;

    DeadLock(boolean flag){
        this.flag = flag;
    }
    // 1.如果flag为 T，线程A就会先得到/持有 o1对象锁，然后尝试去获取 o2对象锁
    // 2.如果线程A得不到o2对象锁，就会Blocked
    // 3.如果flag 为 F，线程B就会先得到/持有o2对象锁，然后尝试去获取o1对象锁
    // 4.如果线程B得不到 o1 对象锁，就会Blocked
    @Override
    public void run() {
        if (flag){

            synchronized (o1){
                System.out.println(Thread.currentThread().getName()+"进入o1-1");

                synchronized (o2){
                    System.out.println(Thread.currentThread().getName()+"进入o1-2");

                }
            }
        }else{
            synchronized (o2){
                System.out.println(Thread.currentThread().getName()+"进入o2-1");

                synchronized (o1){
                    System.out.println(Thread.currentThread().getName()+"进入o2-2");

                }
            }
        }
    }

    public static void main(String[] args) {
        DeadLock deadLock = new DeadLock(true);
        DeadLock deadLock1 = new DeadLock(false);
        deadLock.setName("A");
        deadLock.start();
        deadLock1.setName("B");
        deadLock1.start();
    }
}
